package meatslope2.gameengine.gameobjects;

import java.util.ArrayList;
import java.util.List;

import meatslope2.constants.BitmapConstants;
import meatslope2.constants.TileConstants;
import meatslope2.gameengine.helpers.Utils;
import meatslope2.gameengine.primatives.LineSegment;
import meatslope2.gameengine.primatives.Vector2;

//TODO: detach from inheriting from GameObject 
public class Tile extends GameObject
{
	private final int index;
	public int index()
	{
		return this.index;
	}
	
	private final LineSegment[] lineSegments;
	public LineSegment[] getLineSegments()
	{
		return this.lineSegments;
	}
	
	private Tile(int resourceId, LineSegment[] lineSegments, int index)
	{
		super(resourceId, BitmapConstants.TILE_WIDTH, BitmapConstants.TILE_HEIGHT);
		
		this.lineSegments = lineSegments;
		this.index = index;
	}
	
	@Override
	//TODO: figure out a better way to design gameobject model
	public Vector2 getVelocity() 
	{
		throw new IllegalStateException("velocity is unapplicable to tile objects");
	};
	
	public static class Builder 
	{
		private int resourceId;
		private int index;
		private List<LineSegment> lineSegments;
		
		public Builder()
		{
			reset();
		}
		
		private void reset()
		{
			resourceId = 0;
			index = -1;
			lineSegments = new ArrayList<LineSegment>();
		}
		
		public Builder setIndex(int index)
		{
			if(index < 0)
				throw new IllegalArgumentException("index argument must be zero or greater");
			
			this.index = index;
			return this;
		}
		
		public Builder setResourceId(int resourceId)
		{
			this.resourceId = resourceId;
			return this;
		}
		
		public Builder addLineSegment(LineSegment lineSegment)
		{
			this.lineSegments.add(lineSegment);
			return this;
		}
		
		public Tile build()
		{
			if(this.resourceId == 0)
				throw new IllegalStateException("Tile's resourceId has not been set!");
			else if(this.index == -1)
				throw new IllegalStateException("Tile's index has not been set!");
			
			//Create our tile
			LineSegment[] lineSegmentArray = Utils.toArray(this.lineSegments, new LineSegment[this.lineSegments.size()]);
			Tile newTile = new Tile(this.resourceId, lineSegmentArray, this.index);
			
			//Have TileConstant observe the creation
			TileConstants.observe(newTile);
			
			//Cleanup
			reset();
			
			return newTile;
		}
	}
}
